<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="4">
          <el-input
            v-model="queryData.model.dictName"
            placeholder="名称"
            clearable
            class="filter-input filter-item"
            @keyup.enter.native="getList"
          />
        </el-col>
        <el-col :span="4">
          <el-input
            v-model="queryData.model.dictCode"
            placeholder="编码"
            clearable
            class="filter-input filter-item"
            @keyup.enter.native="getList"
        /></el-col>
      </el-row>
      <div style="float: right">
        <el-button type="primary" class="filter-item" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </el-button>
        <el-button type="primary" class="filter-item" @click="addSpeciality"
          ><el-icon> <Plus /> </el-icon>新增
        </el-button>
        <el-button type="primary" class="filter-item" @click="batchAdjustment"
          ><el-icon> <Edit /> </el-icon>批量编辑
        </el-button>
        <el-button type="primary" class="filter-item" @click="fileDownload"
          ><el-icon> <Download /> </el-icon>下载模板</el-button
        >
        <el-button type="primary" class="filter-item" @click="importFile"
          ><el-icon> <Upload /> </el-icon>导入
        </el-button>
        <input
          type="file"
          @change="onChangeFile"
          ref="fileInput"
          style="display: none"
        />
      </div>
    </div>

    <div id="screenfull-container" style="background-color: #ffffff">
      <div style="width: 100%; text-align: right; float: right">
        <el-icon
          style="
            cursor: pointer;
            margin: 0px 5px 5px 5px;
            font-size: 18px;
            top: -2px;
          "
          @click="handleFullscreen"
        >
          <FullScreen />
        </el-icon>
        <svg-icon
          icon-class="reload"
          style="cursor: pointer; margin: 0px 5px 5px 5px; font-size: 18px"
          @click="getList"
        />
      </div>
      <el-table
        :data="content.list"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        v-loading="loading"
        border
      >
        <el-table-column prop="dictName" label="名称">
          <template #default="{ row }">
            <el-checkbox
              v-if="row.parentId != 0"
              v-model="form2.ids"
              class="table-checkbox"
              :label="row"
            />
            <span style="margin-left: 5px">{{ row.dictName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dictValue" label="编码" />
        <el-table-column prop="type" label="类别">
          <template #default="{ row }">
            <div v-if="row.level === 1">一级分类</div>
            <div v-else-if="row.level === 2" style="margin-left: 28px">
              二级分类
            </div>
            <div v-else style="margin-left: 56px">三级分类</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              v-if="row.level != 3"
              @click="addClassification(row)"
              link
            >
              添加分类
            </el-button>
            <el-button
              type="primary"
              link
              @click="row.parentId == 0 ? edit(row) : edit1(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              placement="top"
              width="160"
              title="是否删除此行?"
              trigger="click"
              @confirm="deleteData(row.id)"
            >
              <template #reference>
                <el-button type="danger" style="margin-left: 10px" link>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-show="content.total > 0"
        :total="content.total"
        v-model:page="queryData.current"
        v-model:limit="queryData.size"
        @pagination="getList"
      />
    </div>

    <el-dialog
      :title="`${form.id ? '编辑' : '新增'}分类`"
      v-model="dialogVisible"
      width="30%"
    >
      <el-form
        :model="form"
        ref="ruleFormRef"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="专业" prop="dictName">
          <el-input v-model="form.dictName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="编码" prop="dictValue">
          <el-input v-model="form.dictValue" style="width: 300px" />
        </el-form-item>
        <el-form-item label="排序" prop="dictSequence">
          <el-input v-model.number="form.dictSequence" style="width: 300px" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitData"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      :title="`${form1.id ? '编辑' : '新增'}分类`"
      v-model="dialogVisible1"
      width="30%"
      :before-close="beforeClose1"
    >
      <el-form
        :model="form1"
        ref="ruleFormRef1"
        label-width="120px"
        :rules="rules1"
      >
        <el-form-item label="分类" prop="dictName">
          <el-input v-model="form1.dictName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="编码" prop="dictValue">
          <el-input v-model="form1.dictValue" style="width: 300px" />
        </el-form-item>
        <el-form-item label="排序" prop="dictSequence">
          <el-input v-model.number="form1.dictSequence" style="width: 300px" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="submitData1"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="批量调整分类"
      v-model="dialogVisible2"
      width="30%"
      :before-close="beforeClose1"
    >
      <el-form
        :model="form2"
        ref="ruleFormRef2"
        label-width="120px"
        :rules="rules2"
      >
        <el-form-item label="移入一级分类" prop="parentId">
          <el-select
            @change="oneChange(form2.parentId)"
            v-model="form2.parentId"
            v-if="form2.ids[0].level == 2 || form2.ids[0].level == 3"
            placeholder="请选择一级分类"
          >
            <el-option
              v-for="v in specialityList"
              :key="v.id"
              :label="v.dictName"
              :value="v.id"
            />
          </el-select>
          <el-cascader
            v-model="form2.parentId"
            v-else
            :options="specialityList"
            :show-all-levels="false"
          />
        </el-form-item>

        <span>
          {{ classificationList }}
        </span>

        <el-form-item
          label="移入二级分类"
          prop="twoId"
          v-if="form2.ids[0].level == 3"
        >
          <el-select
            v-model="form2.twoId"
            v-if="form2.ids[0].level == 3"
            placeholder="请选择二级分类"
          >
            <el-option
              v-for="v in classificationList"
              :key="v.id"
              :label="v.dictName"
              :value="v.id"
            />
          </el-select>
          <el-cascader
            v-model="form2.twoId"
            v-else
            :options="classificationList"
            :show-all-levels="false"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="submitData2"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { ref, reactive, onMounted, watch } from "vue";
import {
  queryModelDictPage,
  insertModelType,
  updateModelType,
  deleteModelType,
  importModelDict,
  downModelDict,
  queryModelFirst,
  queryModelByParentId,
  updateModelTypeBatch,
} from "@/api/buildlibrary";
import { downloadFile } from "@/utils";
import { ElMessage } from "element-plus";

import screenfull from "screenfull";

const queryData = reactive({
  model: {
    dictType: "",
  },
  current: 1,
  size: 10,
});
const loading = ref(false);
const content = reactive({
  list: [],
  total: 0,
});
const getList = async () => {
  try {
    loading.value = true;
    const res = await queryModelDictPage(queryData);
    console.log(res);
    let status = res.code;
    let data = res.data.records;
    let count = res.data.total;
    // const { data, status, count } = data;
    // console.log(data, status, count);
    if (status === 200) {
      content.list = data.map((t) => {
        return {
          ...t,
          level: 1,
          children:
            t.children &&
            t.children.map((c) => {
              return {
                ...c,
                level: 2,
                children:
                  c.children &&
                  c.children.map((o) => {
                    return {
                      ...o,
                      level: 3,
                    };
                  }),
              };
            }),
        };
      });
      content.total = count;
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const oneChange = async (id) => {
  // debugger;
  try {
    const res = await queryModelByParentId(id);
    console.log(res);
    if (resp_code === 200) {
      classificationList.value = datas;
    }
  } catch (error) {}
};

// 添加专业
const dialogVisible = ref(false);
const ruleFormRef = ref();
const rules = reactive({
  dictName: [{ required: true, message: "请输入专业", trigger: "blur" }],
  dictValue: [{ required: true, message: "请输入编码", trigger: "blur" }],
});
let form = reactive({
  dictName: "",
  dictValue: "",
  parentId: 0,
  dictStatus: 0,
  dictSequence: 0,
});
const addSpeciality = () => {
  (form.dictName = ""),
    (form.dictValue = ""),
    (form.parentId = 0),
    (form.dictStatus = 0),
    (form.dictSequence = 0);
  delete form.id;
  dialogVisible.value = true;
};
const submitData = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        ...form,
        dictType: form.dictValue,
      };
      let fun = data.id ? updateModelType : insertModelType;
      const { code } = await fun(data);
      if (code === 200) {
        ElMessage.success(`${data.id ? "编辑" : "添加"}成功`);
        dialogVisible.value = false;
        getList();
      } else {
        ElMessage.error("服务故障，稍后再试");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const edit = (row) => {
  dialogVisible.value = true;
  form.parentId = row.parentId;
  (form.dictName = row.dictName),
    (form.dictValue = row.dictValue),
    (form.parentId = row.parentId),
    (form.dictStatus = 0),
    (form.id = row.id),
    (form.dictSequence = row.dictSequence);
};

// 添加分类
const dialogVisible1 = ref(false);
const ruleFormRef1 = ref();
const rules1 = reactive({
  dictName: [{ required: true, message: "请输入分类", trigger: "blur" }],
  dictValue: [{ required: true, message: "请输入编码", trigger: "blur" }],
});
let form1 = reactive({
  dictName: "",
  dictValue: "",
  dictType: "",
  parentId: 0,
  dictStatus: 0,
  dictSequence: 1,
});
const submitData1 = () => {
  ruleFormRef1.value.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        ...form1,
      };
      let fun = data.id ? updateModelType : insertModelType;
      const { code } = await fun(data);
      if (code === 200) {
        ElMessage.success(`${data.id ? "编辑" : "添加"}成功`);
        dialogVisible1.value = false;
        getList();
      } else {
        ElMessage.error("服务故障，稍后再试");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const addClassification = (row) => {
  form1.dictName = "";
  form1.dictValue = "";
  form1.dictType = "";
  form1.dictStatus = 0;
  form1.dictSequence = 0;
  delete form1.id;
  dialogVisible1.value = true;
  form1.parentId = row.id;
  form1.dictType = row.dictType;
};
const edit1 = (row) => {
  dialogVisible1.value = true;
  form1.parentId = row.parentId;
  (form1.dictName = row.dictName),
    (form1.dictValue = row.dictValue),
    (form1.parentId = row.parentId),
    (form1.dictStatus = 0),
    (form1.id = row.id),
    (form1.dictSequence = row.dictSequence);
};
const beforeClose1 = (done) => {
  form1 = reactive({
    dictName: "",
    dictValue: "",
    dictType: "",
    parentId: 0,
    dictStatus: 0,
    dictSequence: 0,
  });
  done();
};

const deleteData = async (id) => {
  try {
    const { code } = await deleteModelType({ ids: [id] });
    if (code === 200) {
      ElMessage.success(`删除成功`);
      getList();
    } else {
      ElMessage.error(`服务器故障，稍后再试`);
    }
  } catch (error) {}
};
const handleFullscreen = () => {
  const element = document.getElementById("screenfull-container");
  if (screenfull.enabled) {
    screenfull.request(element);
  }
  screenfull.toggle();
};

onMounted(() => {
  getList();
});

// 导入
const fileInput = ref(null);
const importFile = () => {
  fileInput.value.click();
};
const onChangeFile = async () => {
  console.log(fileInput.value.files, "-----");
  try {
    await importModelDict(fileInput.value.files[0]);
    ElMessage.success("导入成功！");
    getList();
  } catch (error) {
    console.log(error, "error");
    // ElMessage.error(error);
  }
};

// 下载模板
const fileDownload = async () => {
  const res = await downModelDict();
  downloadFile(res, "模型分类模板.xlsx");
};

// 子节点批量更换父节点
const specialityList = ref([]);
const classificationList = ref([]);

const dialogVisible2 = ref(false);
const rules2 = reactive({
  parentId: [{ required: true, message: "请选择专业", trigger: "blur" }],
});
const ruleFormRef2 = ref();
let form2 = ref({
  parentId: "",
  ids: [],
});

const batchAdjustment = async () => {
  form.parentId = null;
  form.twoId = null;
  if (form2.value.ids.length <= 0) {
    return ElMessage.warning("请先勾选分类");
  }
  if (!form2.value.ids.every((t) => form2.value.ids[0].level === t.level)) {
    return ElMessage.warning("勾选的分类层级不一致，请重新勾选");
  }
  dialogVisible2.value = true;
  const res = await queryModelFirst();
  specialityList.value = res.data || [];
};

const submitData2 = () => {
  ruleFormRef2.value.validate(async (valid, fields) => {
    if (valid) {
      form2.value.ids = form2.value.ids.map((t) => t.id);
      const { status } = await updateModelTypeBatch(form2.value);
      if (status === 200) {
        ElMessage.success(`批量编辑成功`);
        dialogVisible2.value = false;
        form2.value.ids = [];
        form2.value.parentId = "";
        getList();
      } else {
        ElMessage.error("服务故障，稍后再试");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style lang="scss" scoped>
::v-deep .table-checkbox {
  .el-checkbox__label {
    display: none;
  }
}
</style>
